#!/usr/bin/env bash

set -eo pipefail

WORKSPACE_PATH="${1:-$(pwd)}"

if [[ ! -d "${WORKSPACE_PATH}" || ! "${WORKSPACE_PATH}" = /* || ! -f "${WORKSPACE_PATH}/contrib/guix/guix-build" ]]; then
    echo "${0##*/}: ${WORKSPACE_PATH} is not the top directory of the Dash Core repository, exiting!"
    exit 1
fi

if [[ -z "${HOSTS}" || "${HOSTS}" == *"darwin"* ]]; then
    export SDK_PATH="${SDK_PATH:-${WORKSPACE_PATH}/depends/SDKs}"
    export SDK_SOURCES="${SDK_SOURCES:-${WORKSPACE_PATH}/depends/sdk-sources}"

    ./contrib/containers/guix/scripts/setup-sdk
fi

# Add safe.directory option only when WORKSPACE_PATH was specified via cmd-line arguments (happens in CI)
if [[ -n "${1}" ]]; then
    # Avoid adding duplicates
    git config --global --fixed-value --get safe.directory "${WORKSPACE_PATH}" >> /dev/null || \
        (echo "Adding safe.directory" && git config --global --add safe.directory "${WORKSPACE_PATH}")
fi

cd "${WORKSPACE_PATH}"
git status >> /dev/null

export HOSTS="${HOSTS:-x86_64-linux-gnu aarch64-linux-gnu riscv64-linux-gnu
                       x86_64-w64-mingw32
                       x86_64-apple-darwin arm64-apple-darwin}"

./contrib/guix/guix-build
